package com.xjd.edu.filter;

import com.alibaba.fastjson2.JSON;
import com.xjd.edu.config.AnonymousConfig;
import com.xjd.edu.constant.CacheConstants;
import com.xjd.edu.constant.HttpStatus;
import com.xjd.edu.constant.SecurityConstants;
import com.xjd.edu.constant.TokenConstants;
import com.xjd.edu.model.R;
import com.xjd.edu.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import static com.xjd.edu.config.AppConfig.X_REQUEST_HOST;
import static com.xjd.edu.config.AppConfig.X_REQUEST_ID;

/**
 * 网关鉴权
 *
 * @author ruoyi
 */
@Component
public class EduAuthenticationFilter implements GlobalFilter, Ordered {
    private static final Logger log = LoggerFactory.getLogger(EduAuthenticationFilter.class);

    @Autowired
    private AntPathMatcher matcher;

    @Autowired
    private AnonymousConfig anonymousConfig;

    @Autowired
    private ReactiveStringRedisTemplate redisTemplate;

    /**
     * UTF-8 字符集
     */
    public static final String UTF8 = "UTF-8";


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();
        String path = request.getPath().value();

        // 前一个过滤器有设置，所以这里一定取得到
        String requestId = exchange.getAttribute(X_REQUEST_ID);
        String token = getToken(request);


        // 匿名请求（免登录）
        if (checkAnonymousRequest(path)) {
            return chain.filter(mutateServerWebExchange(exchange, requestId));
        }
        if (StringUtils.isEmpty(token)) {
            return unauthorizedResponse(exchange, "令牌不能为空");
        }
        Claims claims = JwtUtils.parseToken(token);
        if (claims == null) {
            return unauthorizedResponse(exchange, "令牌已过期或验证不正确！");
        }
        String userkey = JwtUtils.getUserKey(claims);
        return redisTemplate.hasKey(getTokenKey(userkey))
                .flatMap(isLogin -> {
                    if (!isLogin) {
                        return unauthorizedResponse(exchange, "登录状态已过期");
                    }
                    String userid = JwtUtils.getUserId(claims);
                    String username = JwtUtils.getUserName(claims);
                    if (StringUtils.isEmpty(userid) || StringUtils.isEmpty(username)) {
                        return unauthorizedResponse(exchange, "令牌验证失败");
                    }

                    // 设置用户信息到请求
                    addHeader(mutate, SecurityConstants.USER_KEY, userkey);
                    addHeader(mutate, SecurityConstants.DETAILS_USER_ID, userid);
                    addHeader(mutate, SecurityConstants.DETAILS_USERNAME, username);
                    addHeader(mutate, X_REQUEST_HOST, exchange.getRequest().getURI().getHost());
                    addHeader(mutate, X_REQUEST_ID, requestId);
                    // 内部请求来源参数清除
                    removeHeader(mutate, SecurityConstants.FROM_SOURCE);
                    return chain.filter(exchange.mutate().request(mutate.build()).build());
                    //return chain.filter(mutateServerWebExchange(exchange.mutate().request(mutate.build()).build(), requestId));
                    //return mutateServerWebExchange(exchange, mutate);
                });
    }

    private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value) {
        if (value == null) {
            return;
        }
        String valueStr = value.toString();
        String valueEncode = urlEncode(valueStr);
        mutate.header(name, valueEncode);
    }

    private void removeHeader(ServerHttpRequest.Builder mutate, String name) {
        mutate.headers(httpHeaders -> httpHeaders.remove(name)).build();
    }

    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg) {
        log.error("[鉴权异常处理]请求路径:{},错误信息:{}", exchange.getRequest().getPath(), msg);
        return webFluxResponseWriter(exchange.getResponse(), msg, HttpStatus.UNAUTHORIZED);
    }

    /**
     * 获取缓存key
     */
    private String getTokenKey(String token) {
        return CacheConstants.LOGIN_TOKEN_KEY + token;
    }

    /**
     * 获取请求token
     */
    private String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(SecurityConstants.AUTHORIZATION_HEADER);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.hasText(token) && token.startsWith(TokenConstants.PREFIX)) {
            token = token.replaceFirst(TokenConstants.PREFIX, "");
        }
        return token;
    }

    /**
     * 检查匿名请求
     *
     * @param action
     * @return
     */
    private boolean checkAnonymousRequest(String action) {
        return anonymousConfig.getAnonUrl().stream().anyMatch(e -> matcher.match(e, action));
    }

    /**
     * 内容编码
     *
     * @param str 内容
     * @return 编码后的内容
     */
    public static String urlEncode(String str) {
        try {
            return URLEncoder.encode(str, UTF8);
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }

    /**
     * 内容解码
     *
     * @param str 内容
     * @return 解码后的内容
     */
    public static String urlDecode(String str) {
        try {
            return URLDecoder.decode(str, UTF8);
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }

    /**
     * 设置webflux模型响应
     *
     * @param response ServerHttpResponse
     * @param value    响应内容
     * @return Mono<Void>
     */
    public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, Object value) {
        return webFluxResponseWriter(response, org.springframework.http.HttpStatus.OK, value, R.FAIL);
    }

    /**
     * 设置webflux模型响应
     *
     * @param response ServerHttpResponse
     * @param code     响应状态码
     * @param value    响应内容
     * @return Mono<Void>
     */
    public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, Object value, int code) {
        return webFluxResponseWriter(response, org.springframework.http.HttpStatus.OK, value, code);
    }

    /**
     * 设置webflux模型响应
     *
     * @param response ServerHttpResponse
     * @param status   http状态码
     * @param code     响应状态码
     * @param value    响应内容
     * @return Mono<Void>
     */
    public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, org.springframework.http.HttpStatus status, Object value, int code) {
        return webFluxResponseWriter(response, MediaType.APPLICATION_JSON_VALUE, status, value, code);
    }

    /**
     * 设置webflux模型响应
     *
     * @param response    ServerHttpResponse
     * @param contentType content-type
     * @param status      http状态码
     * @param code        响应状态码
     * @param value       响应内容
     * @return Mono<Void>
     */
    public static Mono<Void> webFluxResponseWriter(ServerHttpResponse response, String contentType, org.springframework.http.HttpStatus status, Object value, int code) {
        response.setStatusCode(status);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, contentType);
        R<?> result = R.fail(code, value.toString());
        DataBuffer dataBuffer = response.bufferFactory().wrap(JSON.toJSONString(result).getBytes());
        return response.writeWith(Mono.just(dataBuffer));
    }

    /**
     * 改变 ServerWebExchange 对象
     *
     * @param exchange
     * @param requestId
     */

    private ServerWebExchange mutateServerWebExchange(ServerWebExchange exchange, String requestId) {
        return exchange.mutate()
                .request(exchange.getRequest()
                        .mutate()
                        .headers(headers -> {
                            headers.set(X_REQUEST_HOST, exchange.getRequest().getURI().getHost());
                            headers.set(X_REQUEST_ID, requestId);
                            //getAppType(exchange).map(Object::toString).ifPresent(appType -> headers.set(X_APP_TYPE, appType));
                        }).build()
                ).build();
    }

    @Override
    public int getOrder() {
        return -200;
    }
}